package io.xccit.order.service.impl;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import io.xccit.model.order.domain.Order;
import io.xccit.model.product.domain.Product;
import io.xccit.order.feign.ProductFeignClient;
import io.xccit.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import static java.lang.Thread.sleep;

/**
 * @author CH_ywx
 * @version 1.0
 * @create 2025/5/17
 * <p></p>
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ProductFeignClient productFeignClient;

    @SentinelResource(value = "createOrder",blockHandler = "createOrderBlockHandler")
    @Override
    public Order createOrder(Long userId, Long productId) {
//        Product productByRemote = getProductByRemoteWithLoadBalancerAnnotation(productId);
        log.info("调用商品服务获取商品信息时间{}", System.currentTimeMillis());
        Product productByRemote = productFeignClient.getProductById(productId);
        Order order = new Order();
        order.setId(1L);
        order.setTotalAmount(new BigDecimal(String.valueOf(productByRemote.getPrice().multiply(new BigDecimal(productByRemote.getNum())))));
        order.setUserId(userId);
        order.setAddress("甘肃省兰州市城关区雁北路400号");
        order.setProductList(Arrays.asList(productByRemote));
        log.info("调用商品服务获取商品信息后时间{}", System.currentTimeMillis());
        return order;
    }

    /**
     * 兜底方法
     * @param userId
     * @param productId
     * @param e
     * @return
     */
    public Order createOrderBlockHandler(Long userId, Long productId, BlockException e) {
        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(new BigDecimal("0"));
        order.setUserId(0L);
        order.setAddress("异常信息:" + e.getMessage());
        return order;
    }

    /**
     * 远程调用获取商品信息
     * @param productId
     * @return
     */
    public Product getProductByRemote(Long productId) {
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance serviceInstance = instances.get(0);
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/product/" + productId;
        log.info("调用商品服务获取商品信息，url:{}", url);
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    /**
     * 负载均衡远程调用获取商品信息
     * @param productId
     * @return
     */
    public Product getProductByRemoteWithLoadBalancer(Long productId) {
        //轮询负载均衡算法(每个实例都换着来一次)
        ServiceInstance serviceInstance = loadBalancerClient.choose("service-product");
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/product/" + productId;
        log.info("调用商品服务获取商品信息，url:{}", url);
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    /**
     * 注解式负载均衡远程调用获取商品信息
     * @param productId
     * @return
     * @see io.xccit.order.config.RemoteConfig#restTemplate()
     */
    public Product getProductByRemoteWithLoadBalancerAnnotation(Long productId) {
        String url = "http://service-product" + "/product/" + productId;
        log.info("调用商品服务获取商品信息，url:{}", url);
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }
}
